package com.etone.smartAudit.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.etone.smartAudit.domain.*;
import com.etone.smartAudit.dto.item.ItemDTO;
import com.etone.smartAudit.dto.item.ItemExpansionDTO;
import com.etone.smartAudit.dto.item.ItemSourceDTO;
import com.etone.smartAudit.dto.itemSource.DeviceResourceDTO;
import com.etone.smartAudit.dto.task.ItemTaskDTO;
import com.etone.smartAudit.enums.*;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.*;
import com.etone.smartAudit.mapstruct.ItemMapstruct;
import com.etone.smartAudit.utils.ArraysExtendUtil;
import com.etone.smartAudit.utils.BooleanUtil;
import com.etone.smartAudit.utils.ImageUtil;
import com.etone.smartAudit.utils.IpUtil;
import com.etone.smartAudit.vo.FileVO;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.item.*;
import com.etone.smartAudit.vo.serverPath.ServerPathVO;
import com.etone.smartAudit.vo.serviceExpert.ServiceExpertCntVO;
import com.etone.smartAudit.vo.task.ServiceExpertWorkTaskVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.math3.ode.nonstiff.AdamsIntegrator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 蒋学伟
 * @create: 2020-07-16 10:56:53
 * @Description 项目管理
 */
@Service
public class ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemMapstruct itemMapstruct;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ItemExpansionMapper itemExpansionMapper;

    @Autowired
    private ItemExpansionSourceMapper itemExpansionSourceMapper;

    @Autowired
    private ItemSourceMapper itemSourceMapper;

    @Autowired
    private AdminPermissionService adminPermissionService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private ServerInfoMapper serverInfoMapper;

    @Autowired
    private ItemMemberService itemMemberService;

    @Autowired
    private AccountInfoService accountInfoService;

    @Autowired
    private ItemServerPathService itemServerPathService;

    /**
     * 查找项目列表
     *
     * @param admin
     * @param keys
     * @param startCreateTime
     * @param endCreateTime
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ItemListVO> findItemVOList(Admin admin, String keys, Date startCreateTime, Date endCreateTime, int page, int pageSize) {
        boolean hasPermission = adminPermissionService.hasPermission(admin, "show_all_item_list");
        Page<ItemListVO> itemListVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            itemMapper.findItemVOList(hasPermission ? null : admin.getId(), keys, startCreateTime, endCreateTime);
        });
        //id
        List<Integer> itemVOIds = itemListVOPage.stream().map(itemListVO -> itemListVO.getId()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(itemListVOPage)) {
            //获取空间使用情况
            List<ItemSourceUsedVO> itemUsedSpaces = itemMapper.findItemUsedSpace(itemVOIds);

            //遍历项目
            itemListVOPage.forEach(itemListVO -> {

                //填充项目空间使用情况
                List<ItemSourceUsedVO> curItemSourceUsedVO = itemUsedSpaces.stream().filter(itemSourceUsedVO -> itemSourceUsedVO.getItemId().intValue() == itemListVO.getId().intValue()).collect(Collectors.toList());

                //状态是否是正常状态，使用空间大于85%视为异常
                Boolean isNormal = !curItemSourceUsedVO.stream().anyMatch(itemSourceUsedVO ->
                        ItemSourceType.SPACE.equals(itemSourceUsedVO.getItemSourceType()) && itemSourceUsedVO.getSpace() != null && itemSourceUsedVO.getSpaceUsed() != null && (itemSourceUsedVO.getSpaceUsed() / itemSourceUsedVO.getSpace() > 0.85d)
                );

                itemListVO.setSources(curItemSourceUsedVO);
                itemListVO.setIsNormal(isNormal);
            });
        }
        return PagerVO.of(itemListVOPage);
    }


    /**
     * 查找基本信息
     *
     * @param admin
     * @param all
     * @param keys
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ItemSimpleListVO> listItemVOSimpleList(Admin admin, Boolean all, String keys, int page, int pageSize) {
        boolean hasPermission = all || adminPermissionService.hasPermission(admin, "show_all_item_list");
        Page<ItemSimpleListVO> itemListVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            itemMapper.listItemVOSimpleList(hasPermission ? null : admin.getId(), keys, null, null);
        });
        return PagerVO.of(itemListVOPage);
    }

    public Item get(Integer id) {
        Item item = itemMapper.selectById(id);
        if (item == null || !StateType.ENABLE.equals(item.getState())) {
            throw new CustomParameterizedException("项目不存在");
        }
        return item;
    }

    /**
     * 项目详情
     *
     * @param id
     * @return
     */
    public ItemDetailVO detail(Integer id) {
        Item item = get(id);
        ItemDetailVO itemDetailVO = itemMapstruct.getItemDetailVO(item);

        //项目成员
        List<ItemMemberVO> itemMemberVOS = itemMemberService.findByItemId(id);
        itemDetailVO.setItemMembers(itemMemberVOS);

        //扩容记录
        List<ItemExpansionVO> itemExpansionVOS = itemExpansionMapper.findItemExpansionVOByItemId(id);
        itemDetailVO.setItemExpansions(itemExpansionVOS);

        //资源使用情况
        List<ItemSourceUsedVO> itemUsedSpaces = itemMapper.findItemUsedSpace(Arrays.asList(id));
        itemDetailVO.setItemSourceUsed(itemUsedSpaces);
        return itemDetailVO;
    }

    /**
     * 详情基本信息
     *
     * @param id
     * @return
     */
    public ItemBaseVO detailSimple(Integer id) {
        Item item = get(id);
        ItemBaseVO itemBaseVO = itemMapstruct.getItemBaseVO(item);

        //项目成员
        List<ItemMemberVO> itemMemberVOS = itemMemberService.findByItemId(id);
        itemBaseVO.setItemMembers(itemMemberVOS);

        return itemBaseVO;
    }

    /**
     * 获取扩容｜资源申请详情
     *
     * @param itemExpansionId
     * @return
     */
    public ItemExpansion getItemExpansion(Integer itemExpansionId) {
        ItemExpansion itemExpansion = itemExpansionMapper.selectById(itemExpansionId);
        if (itemExpansion == null) {
            throw new CustomParameterizedException("扩容资源不存在");
        }
        return itemExpansion;
    }

    /**
     * 添加项目
     *
     * @param admin
     * @param itemDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer add(Admin admin, ItemDTO itemDTO) {

        if (itemMapper.hasItemName(null, itemDTO.getName())) {
            throw new CustomParameterizedException("项目名称已存在");
        }

        if (itemMapper.hasNameAbbreviation(null, itemDTO.getNameAbbreviation())) {
            throw new CustomParameterizedException("项目缩写已存在");
        }

        Item item = Item
                .builder()
                .checkState(CheckState.CHECKING)
                .createAdminId(admin.getId())
                .createAdminName(admin.getNickName())
                .createTime(new Date())
                .isExpansion(false)
                .isFirstApply(false)
                .isFirstApplyOver(false)
                .state(StateType.ENABLE)
                .build();

        itemMapstruct.copyToItem(item, itemDTO);
        itemMapper.insert(item);

        doAfterSave(item, admin, OperationType.ADD);
        return item.getId();
    }

    /**
     * 编辑项目任务
     *
     * @param id
     * @param itemDTO
     * @param admin
     */
    @Transactional(rollbackFor = Exception.class)
    public void edit(Integer id, ItemDTO itemDTO, Admin admin) {
        if (itemMapper.hasItemName(id, itemDTO.getName())) {
            throw new CustomParameterizedException("项目名称已存在");
        }

        if (itemMapper.hasNameAbbreviation(id, itemDTO.getNameAbbreviation())) {
            throw new CustomParameterizedException("项目缩写已存在");
        }
        Item item = get(id);
        itemMapstruct.copyToItem(item, itemDTO);
        if (!item.getCheckState().equals(CheckState.PASS)) {
            item.setCheckState(CheckState.CHECKING);
        }
        itemMapper.updateById(item);

        doAfterSave(item, admin, OperationType.EDIT);
    }

    /**
     * 增加或者修改后的操作
     *
     * @param item
     * @param admin
     */
    public void doAfterSave(Item item, Admin admin, OperationType operationType) {
        //更新项目成员
        itemMemberService.updateItemMember(item.getId(), item.getItemMembers());

        // 插入任务
        String value = dictionaryService.findValueByCode("item_item_task_checking_member");
        JSONArray jsonArray = JSONArray.parseArray(value);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Integer nodeAdminId = jsonObject.getInteger("id");
        String nodeAdminName = jsonObject.getString("name");

        if (operationType.equals(OperationType.ADD)) {
            String taskName = item.getName() + "-新建项目";
            taskService.add(
                    ItemTaskDTO
                            .builder()
                            .nodeAdminName(nodeAdminName)
                            .nodeAdminId(nodeAdminId)
                            .name(taskName)
                            .itemId(item.getId())
                            .itemTypeId(item.getId())
                            .itemName(item.getName())
                            .info(item)
                            .build(),
                    admin,
                    TaskType.ITEM_ITEM
            );
        } else {
            /**
             * 获取任务
             */
            if (!item.getCheckState().equals(CheckState.PASS)) {
                Task task = taskService.get(item.getId(), TaskType.ITEM_ITEM);
                taskService.edit(
                        task.getId(),
                        ItemTaskDTO
                                .builder()
                                .nodeAdminName(nodeAdminName)
                                .nodeAdminId(nodeAdminId)
                                .name(task.getName())
                                .itemId(item.getId())
                                .itemTypeId(item.getId())
                                .itemName(item.getName())
                                .info(item)
                                .build(),
                        admin,
                        TaskType.ITEM_ITEM
                );
            }
        }


    }

    /**
     * 任务审核
     *
     * @param id
     * @param checkState
     */
    public void check(Integer id, CheckState checkState) {
        Item item = get(id);
        if (CheckState.PASS.equals(checkState)) {
            item.setState(StateType.ENABLE);
        }
        item.setCheckState(checkState);
        itemMapper.updateById(item);
    }

    /**
     * @param admin            审核人
     * @param id               项目id
     * @param itemExpansionDTO 扩容信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void passExpansion(Admin admin, Integer id, ItemExpansionDTO itemExpansionDTO, List<ItemExpansionSourceVO> itemExpansionSourceVOS) {

        if (CollectionUtils.isEmpty(itemExpansionDTO.getItemExpansionSources())) {
            throw new CustomParameterizedException("资源不能为空");
        }

        Date now = new Date();

        Item item = get(id);
        if (BooleanUtil.isTrue(itemExpansionDTO.getIsFirst())) {
            item.setIsFirstApplyOver(true);
            item.setIsFirstApply(true);
        } else {
            item.setIsExpansion(true);
        }
        //更新项目信息
        itemMapper.updateById(item);


        //扩容详情
        ItemExpansion itemExpansion = ItemExpansion
                .builder()
                .itemId(id)
                .createAdminId(admin.getId())
                .createAdminName(admin.getNickName())
                .createTime(now)
                .state(StateType.ENABLE)
                .isFirst(itemExpansionDTO.getIsFirst())
                .checkState(CheckState.PASS)
                .build();
        itemMapstruct.copyToItemExpansion(itemExpansion, itemExpansionDTO);
        itemExpansionMapper.insert(itemExpansion);

        //扩容资源详情
        List<ItemExpansionSource> itemExpansionSources = new ArrayList<>();
        itemMapstruct.copyToItemExpansionSource(itemExpansionSources, itemExpansionDTO.getItemExpansionSources());
        itemExpansionSources.forEach(itemExpansionSource -> itemExpansionSource.setItemExpansionId(itemExpansion.getId()));
        itemExpansionSourceMapper.batchInsert(itemExpansionSources);

        //资源申请添加账号信息
        if (BooleanUtil.isTrue(itemExpansionDTO.getIsFirst())) {
            //增加账号信息
            accountInfoService.add(admin, item, itemExpansionSourceVOS);

            //增加服务器路径
            itemExpansionSourceVOS.stream().filter(itemExpansionSourceVO -> itemExpansionSourceVO.getType() != null && ItemSourceType.SPACE.equals(itemExpansionSourceVO.getType())).forEach(itemExpansionSourceVO -> itemServerPathService.add(id, itemExpansionSourceVO.getServerId(), itemExpansionSourceVO.getPath(), itemExpansionSourceVO.getSpace()));
        }
    }


    /**
     * 查询项目资源基本信息列表
     *
     * @param type
     * @param itemId
     * @param serverId
     * @return
     */
    public List<ItemSourceBaseVO> listItemSourceSimple(ItemSourceType type, Integer itemId, Integer serverId) {
        List<ItemSourceBaseVO> itemSourceBaseVOS = itemSourceMapper.findListItemSourceSimple(type, itemId, serverId);
        return itemSourceBaseVOS;
    }

    /**
     * 查询项目资源列表
     *
     * @param name
     * @param type
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ItemSourceVO> listItemSource(String name, ItemSourceType type, int page, int pageSize) {
        Page<ItemSourceVO> itemSourceVOS = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            itemSourceMapper.findListItemSource(name, type);
        });
        return PagerVO.of(itemSourceVOS);
    }

    /**
     * 获取资源详情
     *
     * @param itemSourceId
     * @return
     */
    public ItemSource getItemSource(Integer itemSourceId) {
        ItemSource itemSource = itemSourceMapper.selectById(itemSourceId);
        if (itemSource == null) {
            throw new CustomParameterizedException("项目资源不存在");
        }
        return itemSource;
    }


    /**
     * 项目资源详情
     *
     * @param itemSourceId
     * @return
     */
    public ItemSourceDetailVO itemSourceDetail(Integer itemSourceId) {
        ItemSource itemSource = getItemSource(itemSourceId);
        return itemMapstruct.getItemSourceDetailVO(itemSource);
    }

    /**
     * 编辑项目资源
     *
     * @param itemSourceId
     * @param itemSourceDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void editItemSource(Integer itemSourceId, ItemSourceDTO itemSourceDTO) {
        ItemSource itemSource = getItemSource(itemSourceId);
        //旧文件
        List<FileVO> oldCover = StringUtils.isEmpty(itemSource.getCover()) ? null : Arrays.asList(JSON.parseObject(itemSource.getCover(), FileVO.class));
        List<FileVO> oldFiles = itemSource.getFiles() == null ? null : JSONArray.parseArray(itemSource.getFiles(), FileVO.class);
        List<String> oldDetailFiles = StringUtils.isEmpty(itemSource.getDetail()) ? null : ImageUtil.getImgTagUrl(itemSource.getDetail());

        BeanUtils.copyProperties(itemSourceDTO, itemSource);
        itemSource.setFiles(itemSourceDTO.getFiles() == null ? null : JSONArray.toJSONString(itemSourceDTO.getFiles()));
        itemSource.setCover(itemSourceDTO.getCover() == null ? null : JSON.toJSONString(itemSourceDTO.getCover()));
        itemSourceMapper.updateById(itemSource);

        //清理图片
        fileUploadService.deleteFileForUpdate(ArraysExtendUtil.mergerArraysList(itemSourceDTO.getFiles(), Arrays.asList(itemSourceDTO.getCover())), ArraysExtendUtil.mergerArraysList(oldCover, oldFiles));
        fileUploadService.deleteFileForUpdateByURL(StringUtils.isEmpty(itemSourceDTO.getDetail()) ? null : ImageUtil.getImgTagUrl(itemSourceDTO.getDetail()), oldDetailFiles);
    }

    /**
     * 更新设备租赁信息
     *
     * @param deviceResourceDTOS
     */
    public void updateItemDeviceResource(List<DeviceResourceDTO> deviceResourceDTOS) {
        for (DeviceResourceDTO deviceResourceDTO : deviceResourceDTOS) {
            Boolean checkExpirationTime = itemSourceMapper.checkDeviceExpirationTime(deviceResourceDTO.getItemSourceId(), null);
            if (checkExpirationTime) {
                throw new CustomParameterizedException(deviceResourceDTO.getItemSourceName() + "已被占用");
            }
        }
        itemSourceMapper.updateItemDeviceResource(deviceResourceDTOS);
    }

    /**
     * 删除项目
     *
     * @param id
     * @param admin
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id, Admin admin) {
        doBeforeDelete(Arrays.asList(id), admin);
        int count = itemMapper.deleteById(id);
        if (count <= 0) {
            throw new CustomParameterizedException("资源不存在");
        }

        doAfterDelete(id);
    }

    /**
     * 批量删除项目
     *
     * @param ids
     * @param admin
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Integer> ids, Admin admin) {
        doBeforeDelete(ids, admin);
        int count = itemMapper.deleteBatchIds(ids);
        if (count <= 0) {
            throw new CustomParameterizedException("资源不存在");
        }

        ids.forEach(id -> doAfterDelete(id));
    }

    /**
     * 删除扩容资源
     * 顺序不能乱，必须先删除已申请的项目资源,才能删除项目扩容详情
     *
     * @param itemId 项目id
     */
    public void deleteItemExpansion(Integer itemId) {

        //1。删除已申请的项目资源
        itemExpansionSourceMapper.deleteByItemId(itemId);

        //2。删除扩容任务
        doAfterDeleteItemExpansion(itemId);

        //3。删除扩容详情
        itemExpansionMapper.deleteByItemId(itemId);


    }

    /**
     * 删除扩容后的操作
     *
     * @param itemId
     */
    public void doAfterDeleteItemExpansion(Integer itemId) {
        List<ItemExpansion> itemExpansions = itemExpansionMapper.findByItemId(itemId);
        if (!CollectionUtils.isEmpty(itemExpansions)) {
            itemExpansions.forEach(itemExpansion -> {
                taskService.deleteByItemTypeId(itemExpansion.getId(), itemExpansion.getIsFirst() ? TaskType.RESOURCE_APPLY : TaskType.RESOURCE_EXPANSION);
            });
        }
    }

    /**
     * 删除资源之前的操作
     *
     * @param ids
     * @param admin
     */
    private void doBeforeDelete(List<Integer> ids, Admin admin) {

        //权限验证
        if (!adminPermissionService.hasPermission(admin, "delete_item_id")) {
            throw new CustomParameterizedException("您没有权限");
        }
    }

    /**
     * 删除资源后的操作
     *
     * @param id
     */
    private void doAfterDelete(Integer id) {

        //删除项目成员
        itemMemberService.deleteByItemId(id);

        //删除扩容记录
        deleteItemExpansion(id);

        //删除项目任务
        taskService.deleteByItemTypeId(id, TaskType.ITEM_ITEM);
    }

    /**
     * 统计项目资源项目个数
     *
     * @return
     */
    public List<ItemSourceUsedTotal> analysisSourceItemCount() {
        return itemMapper.analysisSourceItemCount();
    }

    /**
     * 通过项目资源查询正在使用的项目列表
     *
     * @param itemSourceId
     * @return
     */
    public List<String> findItemNameBySource(Integer itemSourceId) {
        return itemMapper.findItemNameBySource(itemSourceId);
    }

    /**
     * 查询正在进行的项目
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ItemSimpleListVO> listItemOngoing(int page, int pageSize) {
        Page<ItemSimpleListVO> itemSimpleListVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> itemMapper.listItemVOSimpleList(null, null, new Date(), null));
        return PagerVO.of(itemSimpleListVOPage);

    }

    /**
     * 项目类型统计
     *
     * @return
     */
    public ItemTypeCntVO analysisItemTypeCnt() {
        //查询专项审计数量
        Integer specialCnt = itemMapper.analysisSpecialCnt();

        //查询持续审计数量
        Integer riskCnt = itemMapper.analysisRiskCnt();

        //查询其他数量
        Integer otherCnt = itemMapper.analysisNotSpecialCnt();

        return ItemTypeCntVO.builder().riskCnt(riskCnt).specialCnt(specialCnt).otherCnt(otherCnt).build();
    }

    /**
     * 项目资源关系
     *
     * @return
     */
    public List<ItemResourceRelation> resourceRelations() {
        List<ItemResourceRelation> itemResourceRelations = new ArrayList<>();
        List<Task> tasks = itemMapper.resourceRelations();

        //获取所有的服务器
        List<ServerInfo> serverInfos = serverInfoMapper.selectList(null);
        //ip对应服务器id信息
        Map<String, Integer> serverIpMaps = serverInfos.stream().filter(serverInfo -> StringUtils.hasText(serverInfo.getIp())).collect(Collectors.toMap(ServerInfo::getIp, ServerInfo::getId));

        tasks.forEach(task -> {

            Optional<ItemResourceRelation> filterItemResourceRelationOptional = itemResourceRelations.stream().filter(itemResourceRelation -> itemResourceRelation.getId().intValue() == task.getItemId().intValue()).findFirst();
            ItemResourceRelation itemResourceRelation;
            if (filterItemResourceRelationOptional.isPresent()) {
                itemResourceRelation = filterItemResourceRelationOptional.get();
            } else {
                itemResourceRelation = ItemResourceRelation.builder().id(task.getItemId()).name(task.getItemName()).build();
                itemResourceRelations.add(itemResourceRelation);
            }

            String detail = task.getDetail();
            switch (task.getType()) {
                //服务支撑中台任务
                case WORK_SERVICE: {
                    //解析json
                    ServiceExpertWorkTaskVO workTaskDetailVO = JSON.parseObject(detail, ServiceExpertWorkTaskVO.class);
                    List<ServiceExpertCntVO> serviceExpertCnts = workTaskDetailVO.getServiceExpertCnt();

                    //获取支撑专家
                    List<Integer> serviceExpertBaseVOS = serviceExpertCnts.stream().filter(serviceExpertCnt -> serviceExpertCnt.getId() != null).map(serviceExpertCntVO -> serviceExpertCntVO.getId()).collect(Collectors.toList());
                    List<Integer> serviceExperts = itemResourceRelation.getServiceExpertIds();
                    if (serviceExperts == null) {
                        itemResourceRelation.setServiceExpertIds(serviceExperts = new ArrayList<>());
                    }
                    serviceExperts.addAll(serviceExpertBaseVOS);

                }
                break;
                default:
                    List<Integer> serverInfoIds = itemResourceRelation.getServerInfoIds();
                    if (CollectionUtils.isEmpty(serverInfoIds)) {
                        itemResourceRelation.setServerInfoIds(serverInfoIds = new ArrayList<>());
                    }
                    //提取ip
                    List<String> ips = IpUtil.getJsonIps(detail);
                    if (!CollectionUtils.isEmpty(ips)) {
                        List<Integer> ipIds = ips.stream().filter(ip -> StringUtils.hasText(ip)).map(ip -> serverIpMaps.get(ip)).collect(Collectors.toList());
                        serverInfoIds.addAll(ipIds);
                        itemResourceRelation.setServerInfoIds(serverInfoIds);
                    }
            }
        });
        //去重
        if (!CollectionUtils.isEmpty(itemResourceRelations)) {
            itemResourceRelations.forEach(itemResourceRelation -> {
                if (!CollectionUtils.isEmpty(itemResourceRelation.getServiceExpertIds())) {
                    itemResourceRelation.setServiceExpertIds(itemResourceRelation.getServiceExpertIds().stream().distinct().collect(Collectors.toList()));
                }
                if (!CollectionUtils.isEmpty(itemResourceRelation.getServerInfoIds())) {
                    itemResourceRelation.setServerInfoIds(itemResourceRelation.getServerInfoIds().stream().distinct().collect(Collectors.toList()));
                }
            });
        }

        return itemResourceRelations;
    }

    /**
     * 项目硬件资源信息列表
     *
     * @param id
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ServerPathVO> listItemHardware(Integer id, int page, int pageSize) {
        Page<ServerPathVO> serverPathVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> itemMapper.findListItemHardware(id));
        return PagerVO.of(serverPathVOPage);
    }

    /**
     * 项目软件资源
     *
     * @param id
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ItemSoftwareVO> listItemSoftware(Integer id, int page, int pageSize) {
        Page<ItemSoftwareVO> itemSoftwareVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> itemMapper.listItemSoftware(id));
        return PagerVO.of(itemSoftwareVOPage);
    }

    /**
     * 项目资源申请总情况
     *
     * @param id 项目id
     * @return
     */
    public List<ItemSourceUsedVO> itemSourceApplyTotal(Integer id) {
        return itemExpansionSourceMapper.itemSourceApplyTotal(id);
    }


    /***
     * 获取指定用户负责的项目
     * @param adminId
     * @return
     */
    public List<Item> getItemsByAdminId(Integer adminId) {
        //获取项目列表
        List<Item> list = itemMapper.getItemsByUserId(adminId);
        return list;
    }

    /***
     * 获取指定用户负责的项目
     * @param admin
     * @return
     */
    public List<ItemSimpleListVO> getSelfItems(Admin admin) {
        if (admin.isAdmin()) {
            return getItemsByAdmin(admin);
        }
        //获取项目列表
        List<Item> list = itemMapper.getItemsByUserId(admin.getId());
        List<ItemSimpleListVO> items = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(item -> {
                ItemSimpleListVO vo = new ItemSimpleListVO();
                BeanUtils.copyProperties(item, vo);
                items.add(vo);
            });
        }
        return items;
    }

    /***
     * 获取指定用户负责的项目
     * @param admin
     * @return
     */
    public List<ItemSimpleListVO> getItemsByAdmin(Admin admin) {
        //获取项目列表
        PagerVO<ItemSimpleListVO> vo = listItemVOSimpleList(admin, false, null, 1, 1000);
        return vo.getRows();
    }

    public Item getItemById(Integer id) {
        return itemMapper.selectById(id);
    }
}
